package com.qpx.eurekamongodb.service;


import com.qpx.dto.LogDto;
import com.qpx.eurekamongodb.entity.LogEntity;
import com.qpx.vo.ResultEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class LogService {


    @Autowired
    MongoTemplate mongoTemplate;

    public void save(LogEntity logEntity){
        mongoTemplate.save(logEntity);
    }


    public ResultEntity find(LogDto logDto){
        Query query = new Query();
        if (StringUtils.isNotBlank(logDto.getMethodName())){
             query = Query.query(Criteria.where("methodName").is(logDto.getMethodName()));
        }
        if (StringUtils.isNotBlank(logDto.getServerPort())){
            query.addCriteria(Criteria.where("serverPort").is(logDto.getServerPort()));
        }
        long count = mongoTemplate.count(query, LogEntity.class);

        query.skip((logDto.getPageNo()-1)*logDto.getPageSize());
        query.limit(logDto.getPageSize());

        List<LogEntity> logEntities = mongoTemplate.find(query, LogEntity.class);
        Map<String,Object> map = new HashMap<String,Object>(){{
            put("total",count);
            put("content",logEntities);
        }};
        return ResultEntity.ok("200","查询成功",map);

    }
}
